package com.jeedcp.gen.controller;

import com.jeedcp.gen.entity.DoGenerate;
import com.jeedcp.gen.model.GenTableColumn;
import com.jeedcp.gen.service.SysGeneratorService;
import com.jeedcp.gen.utils.DBUtil;
import com.jeedcp.gen.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/devtools/v1/crud")
public class CrudController {

	@Autowired
	private SysGeneratorService sysGeneratorService;
	@RequestMapping("/doGenerate")
	public R getTables(@RequestBody DoGenerate doGenerate) {
		String[] tableNames=new String[]{doGenerate.getModel().getTable()};
		String templateName="Common"+"Controller";
		if (doGenerate.getLayers().size()>0){//生成前端代码的条件
			templateName=templateName+"View";
		}
		String sql3 = "SELECT * from menu where name='" + doGenerate.getMenu().getName() + "' and link='"+'/'+doGenerate.getModel().getTable()+'/'+"'";
		List<Map<String, Object>> stringList0 = null;
		try {
			stringList0 = DBUtil.query(sql3);
		} catch (SQLException e) {
			return R.ok("新增菜单失败");
		}
		if (stringList0.size() > 0) {
			return R.ok("菜单已存在！");
		}
		String sql1 = "INSERT INTO menu (parent_id, type,application, name,icon,link,sort_id) VALUES ('"+doGenerate.getMenu().getParentId()+"', 'PC', 'MS','"+doGenerate.getMenu().getName()+"','"+doGenerate.getMenu().getIcon()+"','"+'/'+doGenerate.getModel().getTable()+'/'+"','999')";
		try {
			DBUtil.executeUpdateFH(sql1);
		} catch (Exception e) {
			return R.ok("新增菜单失败");
		}
		sysGeneratorService.generatorCode(tableNames,templateName);
		return R.ok("操作成功: 代码已生成，重新编译运行后生效！");
	}
//	/**
//	 * 生成代码
//	 */
//	@RequestMapping("/code")
//	public String code(String tables,String templateName) throws IOException {
//		 sysGeneratorService.generatorCode(tables.split(","),templateName);
//	     return "success";
//	}

}
